package com.cb.domain.service.system.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cb.core.service.cache.CacheEntityManagerImpl;
import com.cb.core.service.cache.EntityManager;
import com.cb.domain.dao.system.AppRoleDAO;
import com.cb.domain.model.system.AppResource;
import com.cb.domain.model.system.AppRole;
import com.cb.domain.service.system.AppRoleManager;

/**
 * manage categories from cache
 * @author yhj
 */
//@Service
public class CacheAppRoleManagerImpl extends CacheEntityManagerImpl<AppRole, Long> implements AppRoleManager{

	@Autowired
	public CacheAppRoleManagerImpl(AppRoleDAO appRoleDAO) {
		super(appRoleDAO);
		// TODO Auto-generated constructor stub
	}

	private AppRoleManager dbAppRoleManager;
	private Map<String, String[]> authorityRoleUrlMapping;
	
	@Override
	public void initialize() {
		super.initialize();
		reloadRoleUrlMapping();
	}

	public void reloadRoleUrlMapping() {
		authorityRoleUrlMapping = new HashMap();
		List<AppRole> roles = getAll();
		for (AppRole appRole : roles) {
			Set resources = appRole.getResources();
			String[] rescourceUrls = null; 
			for (Iterator iterator = resources.iterator(); iterator.hasNext();) {
				AppResource resource = (AppResource) iterator.next();
				rescourceUrls = (String[])ArrayUtils.add(rescourceUrls, resource.getResourceUrl());
			}
			authorityRoleUrlMapping.put(appRole.getAuthority(), rescourceUrls);
		}
	}
	
	public Map<String, String[]> getRoleUrlMapping() {
		return authorityRoleUrlMapping;
	}

	public List getUnselectedRoles(Long userId) {
		return dbAppRoleManager.getUnselectedRoles(userId);
	}
	
	protected String[] fetchRelateObject() {
		return new String[]{"resources"};
	}

	@Override
	protected EntityManager<AppRole, Long> getDbEntityManager() {
		return dbAppRoleManager;
	}
	
	public void setDbAppRoleManager(AppRoleManager dbAppRoleManager) {
		this.dbAppRoleManager = dbAppRoleManager;
	}
	
}
